package com.example.java_gobang.api;

import com.example.java_gobang.game.OnlineUserManager;
import com.example.java_gobang.model.User;
import com.example.java_gobang.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private OnlineUserManager onlineUserManager;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request) {
        if (username == null || username.trim().isEmpty()) {
            return new ErrorResponse("请输入用户名");
        }
        if (password == null || password.trim().isEmpty()) {
            return new ErrorResponse("密码不能为空");
        }

        // 查询用户
        User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            return new ErrorResponse("账号或者密码错误");
        }

        // 检查用户是否已经在线
        if (onlineUserManager.getFromGameHall(user.getUserId()) != null ||
                onlineUserManager.getFromGameRoom(user.getUserId()) != null) {
            return new ErrorResponse("该账号已经在其他地方登录！");
        }

        // 登录成功
        HttpSession httpSession = request.getSession(true);
        httpSession.setAttribute("user", user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password, String confirmPassword) {
        // 检查用户名和密码是否为空
        if (username == null || username.trim().isEmpty()) {
            return new ErrorResponse("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            return new ErrorResponse("密码不能为空");
        }

        // 检查密码长度是否大于6
        if (password.length() < 6) {
            return new ErrorResponse("密码长度至少为6");
        }

        // 检查密码强度（至少包含两种类型的字符：大写字母、小写字母、数字、特殊字符）
        int strength = 0;
        if (password.matches(".*[A-Z].*")) strength++;
        if (password.matches(".*[a-z].*")) strength++;
        if (password.matches(".*\\d.*")) strength++;
        if (password.matches(".*[^A-Za-z0-9].*")) strength++;

        if (strength < 2) {
            return new ErrorResponse("密码强度不够，至少包含两种类型的字符");
        }

        // 检查两次输入的密码是否一致
        if (!password.equals(confirmPassword)) {
            System.out.println("两次输入的密码不一致");
            return new ErrorResponse("两次输入的密码不一致");
        }

        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setScore(1200);
            user.setWinCount(0);
            user.setTotalCount(0);
            userMapper.insert(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            return new ErrorResponse("用户名已存在");
        }
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request) {
        try {
            HttpSession httpSession = request.getSession(false);
            if (httpSession == null) {
                return new ErrorResponse("未登录");
            }
            User user = (User) httpSession.getAttribute("user");
            if (user == null) {
                return new ErrorResponse("未登录");
            }
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            return new ErrorResponse("获取用户信息失败");
        }
    }

    public static class ErrorResponse {
        private String message;

        public ErrorResponse(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}
